<template>
    <Dialog v-model="dialogVisible" :title="title">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        v-loading="formLoading"
        label-width="200px"
      >
        <el-form-item label="pc模板" prop="pcSolution">
          <el-select v-model="formData.pcSolution" placeholder="pc模板">
            <el-option v-for="item in solutions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="h5模板" prop="h5Solution">
          <el-select v-model="formData.h5Solution" placeholder="h5模板">
            <el-option v-for="item in solutions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="平台" prop="formData.platformId">
          <el-radio-group v-model="formData.platformId" @change="changePlatformQuery" class="ml-4">
            <el-radio
              v-for="(dict, index) in platforms"
              :key="index"
              :label="dict.value"
              :value="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="首页模板" prop="formData.indexTpl">
          <el-select v-model="formData.indexTpl" class="w-full">
            <el-option v-for="item in indexTemplates" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="列表页模板" prop="formData.defListTpl">
          <el-select v-model="formData.defListTpl" class="w-full">
            <el-option
              v-for="item in channelListTemplates"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="详情页模板" />
        <el-form-item
          v-for="contentModelTpl in formData.contentDefTpls"
          :label="contentModelTpl.modelName"
          :key="contentModelTpl"
        >
          <el-select v-model="contentModelTpl.detailTpl" class="w-full">
            <el-option
              v-for="item in contentDetailTemplates"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 操作按钮 -->
      <!-- 按钮：保存 -->
      <XButton type="primary" :title="t('action.save')" @click="submitForm(formRef)" />
    </Dialog>
</template>
<script setup lang="ts">
defineOptions({ name: 'SiteTplConfigForm' })
import { getSiteTplConfigApi, updateSiteTplConfigApi } from '@/api/cms/site'
import {
  getChannelListAllTpls,
  getContentDetailAllTpls,
  getIndexTpl
} from '@/api/cms/tpl'
import * as TplApi from '@/api/cms/tpl'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const title = ref('站点默认模板配置')
const dialogVisible = ref(false) // 弹窗的是否展示
const platforms = getIntDictOptions(DICT_TYPE.CMS_STATICPAGEPLATFORMS)
// 表单校验
const rules = reactive({
  platformId: [required],
  siteId: [required]
})
const queryData = ref({
  siteId: 1,
  platformId: 1
})
const formData = ref({
  id: undefined,
  platformId: 1,
  siteId: 1,
  indexTpl: '',
  defListTpl: '',
  contentDefTpls: [],
  pcSolution: '',
  h5Solution: ''
})
const indexTemplates = ref<any[]>([])
const channelListTemplates = ref<any[]>([])
const contentDetailTemplates = ref<any[]>([])
const fetchIndexTemplates = async (pc: boolean) => {
  indexTemplates.value = await getIndexTpl(pc)
}
const fetchChannelTemplates = async (pc: boolean) => {
  channelListTemplates.value = await getChannelListAllTpls(pc)
}
const fetchContentTemplates = async (pc: boolean) => {
  contentDetailTemplates.value = await getContentDetailAllTpls(pc)
}
watch(dialogVisible, async () => {
  if (dialogVisible.value) {
    await fetchIndexTemplates(formData.platformId == 1)
    await fetchChannelTemplates(formData.platformId == 1)
    await fetchContentTemplates(formData.platformId == 1)
  }
})
const formRef = ref() // 表单 Ref
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

const open = async (id: number) => {
  dialogVisible.value = true
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    queryData.value.siteId = id
    queryData.value.platformId = platforms[0].value
    try {
      formData.value = await getSiteTplConfigApi(queryData.value)
    } finally {
      formLoading.value = false
    }
  }
}
const solutions = ref() //模板文件夹结构
// 获取下拉框[模板]的数据
const getSolutions = async () => {
  solutions.value = await TplApi.getSiteTplSolutionApi()
}
const changePlatformQuery = async (value) => {
  await fetchIndexTemplates(value == 1)
  await fetchChannelTemplates(value == 1)
  //重新拉取站点模板配置数据
  queryData.value.platformId = value
  formData.value = await getSiteTplConfigApi(queryData.value)
}

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
// 提交按钮
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    await updateSiteTplConfigApi(formData.value)
    message.success(t('common.updateSuccess'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
  dialogVisible.value = false
  // 发送操作成功的事件
  emit('success')
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
onMounted(async () => {
  await getSolutions()
})
</script>
<style scoped>
.watermark-txt-color-block {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.el-form .el-input {
  width: 150px;
}
</style>
